(function(window, document) {
  var dog = { //声明一个命名空间，或者称为对象
    $: function(id) {
      return document.querySelector(id);
    },
    on: function(el, type, handler) {
      el.addEventListener(type, handler, false);
    },
    off: function(el, type, handler) {
      el.removeEventListener(type, handler, false);
    }
  };
  //封装一个滑块类
  function Slider(boxid) {
    var args = arguments[0];
    for (var i in args) {
      this[i] = args[i]; //一种快捷的初始化配置
    }
    //直接进行函数初始化，表示生成实例对象就会执行初始化
    this.init(boxid);
  }
  Slider.prototype = {
    constructor: Slider,
    init: function(boxid) {
      this.getDom(boxid);
      this.dragBar(this.handler,boxid);
    },
    getDom: function(boxid) {
      this.slider = dog.$('#' + this.id);
      this.handler = $(this.slider).find('.handler')[0];
      this.bg = $(this.slider).find('.drag_bg')[0];
      console.log(this.slider)
    },
    dragBar: function(handler,boxid) {
      var that = this,
        startX = 0,
        lastX = 0,
        doc = document,
        width = this.slider.offsetWidth,
        max = width - handler.offsetWidth;

      function down(e) {
        $(that.bg).removeClass('ani');
        $(handler).removeClass('ani');
        var e = e || window.event;
        $(that.slider).addClass('unselect');
        startX = e.clientX - handler.offsetLeft;
        //console.log('startX: ' + startX + ' px');
        $(doc).on('mouseup', function() {
          $(doc).off('mousemove', move);
          $(doc).off('mouseup', up);
        });
        $(doc).on('mousemove', move);
        $(doc).on('mouseup', up);
        return false;
      };

      function move(e) {
        var e = e || window.event;
        lastX = e.clientX - startX;
        lastX = Math.max(0, Math.min(max, lastX)); //这一步表示距离大于0小于max，巧妙写法
        //console.log('lastX: ' + lastX + ' px');
        if (lastX >= max) {
          $(handler).addClass('handler_ok_bg');
          $(that.slider).addClass('slide_ok');
          console.log(lastX,max)
          //dog.off(handler,'mousedown',down);
          $(handler).off('mousedown', down);
          $(handler).parent().find(".drag_text").text("验证码已发送");
          up();
          //alert(lastX)
        }
        $(that.bg).css("width", lastX);
        $(handler).css("left", lastX);
      };

      function up(e) {
        var e = e || window.event;
        $(that.slider).removeClass('unselect');
        if (lastX < width) {
          $(that.bg).addClass('ani');
          $(handler).addClass('ani');
          that.bg.style.width = 0;
          handler.style.left = 0;
          setTimeout(function() {
            $(that.bg).remove('ani');
            $(handler).remove('ani');
          }, 300);
        }
        $(doc).off('mousemove', move);
        $(doc).off('mouseup', up);
      };
      $(handler).on('mousedown', down);

    }
  };
  window.SB = window.Slider = Slider;


})(window, document);